#include <Starter.hpp>


int Starter::start(Config &config){


	/* Init semaphore to handle the connection number */
	sem_t connectionCountSem;
	sem_init(&connectionCountSem, 0, config.getConnections());

	/* Init a TCP/IP Server on the given port */
	TCPServer tcpServer(config.getPort(), config.isIPv6Flag());

	std::cout << "---------------------------------" << std::endl;
	std::cout << "NetCalc Server" << std::endl;
	std::cout << "Waiting for connection: " << std::endl;
	std::cout << " -Port " << config.getPort() << std::endl;
	std::cout << " -Using: IPv";
	if(config.isIPv6Flag()){
		std::cout << "6" << std::endl;
	}else{
		std::cout << "4" << std::endl;
	}
	std::cout << " -Connection slots: " << config.getConnections() << std::endl;
	std::cout << "---------------------------------" << std::endl;

	while(true){

		/* Wait for an incoming connection */
		TCPConnection *tcpConnection = tcpServer.waitForConnection();


		/* Try to wait for a free connection slot */
		errno = 0;
		sem_trywait(&connectionCountSem);

		if(errno == EAGAIN){
			/* Semaphore is already zero, therefore refuse new connection */
			std::cout << "Rejected connection!" << std::endl;
			tcpConnection->closeConnection();
		}else{
			/* Start a new thread to serve the client */
			SessionThread *sessionThread;
			sessionThread = new SessionThread(tcpConnection, &connectionCountSem);
		}

	}

	return 0;
}

